package net.zhengxinyun.performance.service.measurement;

import com.sirdc.modules.core.exceptions.ServiceException;
import com.yunpian.sdk.model.SmsSingleSend;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.data.MeasurementData;
import net.zhengxinyun.performance.entity.EvaluateUserEntity;
import net.zhengxinyun.performance.entity.MeasurementInformationEntity;
import net.zhengxinyun.performance.entity.QuestionEntity;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.mapper.login.EvaluateUserEntityMapper;
import net.zhengxinyun.performance.mapper.measurement.AnswerEntityMapper;
import net.zhengxinyun.performance.mapper.measurement.MeasurementInformationEntityMapper;
import net.zhengxinyun.performance.mapper.measurement.QuestionEntityMapper;
import net.zhengxinyun.performance.yunpian.YunpianService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;


/**
 * Created by hyp1202 on 2018/12/29.
 */
@Service
@Transactional
public class AssessmentTestServiceImpl implements AssessmentTestService {

    @Value("${path}")
    public String PATH ;

    private MeasurementInformationEntityMapper measurementInformationEntityMapper;
    private QuestionEntityMapper questionEntityMapper;
    private EvaluateUserEntityMapper evaluateUserEntityMapper;
    private YunpianService yunpianService;
    private AnswerEntityMapper answerEntityMapper;
    private MeasurementData measurementData;

    @Autowired
    public AssessmentTestServiceImpl(MeasurementInformationEntityMapper measurementInformationEntityMapper, QuestionEntityMapper questionEntityMapper, EvaluateUserEntityMapper evaluateUserEntityMapper, YunpianService yunpianService, AnswerEntityMapper answerEntityMapper, MeasurementData measurementData) {
        this.measurementInformationEntityMapper = measurementInformationEntityMapper;
        this.questionEntityMapper = questionEntityMapper;
        this.evaluateUserEntityMapper = evaluateUserEntityMapper;
        this.yunpianService = yunpianService;
        this.answerEntityMapper = answerEntityMapper;
        this.measurementData = measurementData;
    }

    @Override
    public String insert(MeasurementInformationEntity measurementInformationEntity, List<QuestionEntity> list) {
        String date = DateUtils.getDate();
        int compareDate = DateUtils.compareDate(date,measurementInformationEntity.getStartTime());
        if (-1 == compareDate){
            measurementInformationEntity.setStatus("0");
        }else {
            measurementInformationEntity.setStatus("1");
        }
        int i = measurementInformationEntityMapper.insert(measurementInformationEntity);
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "测评添加失败";
        }
        int a;
        for (QuestionEntity question : list) {
            question.setMeasurementId(measurementInformationEntity.getId());
            a = questionEntityMapper.insert(question);
            if (a == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "题目添加失败";
            }
        }
        return "添加成功";
    }

    @Override
    public String update(MeasurementInformationEntity measurementInformationEntity, List<QuestionEntity> list) {
        int i = measurementInformationEntityMapper.updateByPrimaryKeySelective(measurementInformationEntity);
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "测评修改失败，请重试";
        }

        int x;
        x = questionEntityMapper.deleteByMeaId(measurementInformationEntity.getId());
        if (x == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "题目修改失败，请重试";
        }
        int a;
        for (QuestionEntity question : list) {
            question.setMeasurementId(measurementInformationEntity.getId());
            a = questionEntityMapper.insertSelective(question);
            if (a == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "题目修改失败，请重试";
            }
        }
        return "修改成功";
    }

    @Override
    public String delete(MeasurementInformationEntity measurementInformationEntity) {
        int i = measurementInformationEntityMapper.deleteByPrimaryKey(measurementInformationEntity.getId());
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "测评删除失败，请重试";
        }
        int a = questionEntityMapper.deleteByMeaId(measurementInformationEntity.getId());
        if (a == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "测评删除失败，请重试";
        }
        return "测评删除成功";
    }

    @Override
    public List<MeasurementInformationFilter> query(MeasurementInformationFilter measurementInformationFilter) {
        List<MeasurementInformationFilter> list = measurementInformationEntityMapper.query(measurementInformationFilter);
        return list;
    }

    @Override
    public Integer queryForCount(MeasurementInformationFilter measurementInformationFilter) {
        return measurementInformationEntityMapper.queryForCount(measurementInformationFilter);
    }


    /**
     * 返回具体测评卷内容
     * @param measurementInformationFilter
     * @return
     */
    @Override
    public HashMap<String, Object> queryForPaper(MeasurementInformationFilter measurementInformationFilter) {
        HashMap<String, Object> map = new HashMap<>();
        MeasurementInformationEntity entity = measurementInformationEntityMapper.selectByPrimaryKey(measurementInformationFilter.getId());
        map.put("information", entity);
        QuestionFilter questionFilter = new QuestionFilter();
        questionFilter.setMeasurementId(measurementInformationFilter.getId());
        questionFilter.setType("0");
        List<QuestionFilter> singleList = questionEntityMapper.queryForNumber(questionFilter);
        map.put("singleList", singleList);
        questionFilter.setType("1");
        List<QuestionFilter> shortList = questionEntityMapper.queryForNumber(questionFilter);
        map.put("shortList",shortList);
        questionFilter.setType("2");
        List<QuestionFilter> multipleList = questionEntityMapper.queryForNumber(questionFilter);
        map.put("multipleList",multipleList);
        return map;
    }

    /**
     * 返回具体测评卷内容
     * @param measurementInformationFilter
     * @param evaluateUserEntity
     * @return
     * @throws Exception
     */
    public HashMap<String, Object> queryForPaper(MeasurementInformationFilter measurementInformationFilter, EvaluateUserEntity evaluateUserEntity) throws Exception {
        AnswerFilter answerFilter = new AnswerFilter();
        answerFilter.setMeasurementId(measurementInformationFilter.getId());
        answerFilter.setRespondents(evaluateUserEntity.getPhone());
        List<AnswerFilter> list = answerEntityMapper.query(answerFilter);
        if (list.size() != 0){
            throw new Exception("已进行过此份测评");
        }
        HashMap<String, Object> map = new HashMap<>();
        MeasurementInformationEntity entity = measurementInformationEntityMapper.selectByPrimaryKey(measurementInformationFilter.getId());
        map.put("information", entity);
        QuestionFilter questionFilter = new QuestionFilter();
        questionFilter.setMeasurementId(measurementInformationFilter.getId());
        questionFilter.setType("0");
        List<QuestionFilter> singleList = questionEntityMapper.queryForNumber(questionFilter);
        map.put("singleList", singleList);
        questionFilter.setType("1");
        List<QuestionFilter> shortList = questionEntityMapper.queryForNumber(questionFilter);
        map.put("shortList",shortList);
        questionFilter.setType("2");
        List<QuestionFilter> multipleList = questionEntityMapper.queryForNumber(questionFilter);
        map.put("multipleList",multipleList);
        return map;
    }

    /**
     * 导入测评卷
     * @param file
     * @return
     */
    @Override
    public String importMeasurement(MultipartFile file) {
        if (file.getOriginalFilename().endsWith(".xls") == false && file.getOriginalFilename().endsWith(".xlsx") == false) {
            return "文件后缀不对";
        }
        String filePath;
        try {
            Util.write(file.getOriginalFilename(),file.getInputStream());
            filePath = this.PATH+file.getOriginalFilename();
            filePath = new String(filePath.getBytes("utf-8"),"utf-8");
            if (StringUtils.isBlank(filePath)){
                return "filePath为空";
            }
            Map<String,Object> map = measurementData.improtMeasurementInformation(filePath);
            Long measurementId = 0L;
            for (Map.Entry<String,Object> entry:map.entrySet()){
                String str = entry.getKey();
                if ("measurement".equals(str)){
                    List<MeasurementInformationEntity> list = (List<MeasurementInformationEntity>) map.get(str);
                    for (MeasurementInformationEntity entity:list) {
                        int i = measurementInformationEntityMapper.insert(entity);
                        if (i == 0){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return "导入失败，请重试";
                        }
                        measurementId = entity.getId();
                    }
                }
                if ("question".equals(str)){
                    List<QuestionEntity> list = (List<QuestionEntity>) map.get(str);
                    for (QuestionEntity entity:list){
                        entity.setMeasurementId(measurementId);
                        int i = questionEntityMapper.insert(entity);
                        if (i == 0){
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return "导入失败，请重试";
                        }
                    }
                }
//                List list = (List) map.get(str);
//                String name = list.get(0).getClass().getName();
//                if ("QuestionEntity".equals(name)){
//                    for (Object obj:list) {
//                        QuestionEntity question = (QuestionEntity) obj;
//                        int i = questionEntityMapper.insert(question);
//                        if (i == 0){
//                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                            return "导入失败，请重试";
//                        }
//                    }
//                }else {
//                    for (Object obj : list){
//                        MeasurementInformationEntity entity = (MeasurementInformationEntity) obj;
//                        int i = measurementInformationEntityMapper.insert(entity);
//                        if (i == 0){
//                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                            return "导入失败，请重试";
//                        }
//                    }
//                }
            }
            return "导入成功";
        }catch (Exception e){
            return "导入失败";
        }
    }

    /**
     * 设置最后得分
     * @param measurementInformationEntity
     * @return
     */
    @Override
    public MeasurementInformationEntity setFinalPoint(MeasurementInformationEntity measurementInformationEntity) {
        AnswerFilter answerFilter = new AnswerFilter();
        answerFilter.setMeasurementId(measurementInformationEntity.getId());
        List<AnswerFilter> list = answerEntityMapper.queryForAnswerCount(answerFilter);
        Double scoreA = 0.0;
        Double scoreB = 0.0;
        Double scoreC = 0.0;
        Double scoreD = 0.0;
        Double scoreE = 0.0;
        Double scoreF = 0.0;
        for (AnswerFilter filter:list) {
            if (StringUtils.isNotBlank(filter.getOptionANum())){
                scoreA += Double.valueOf(filter.getOptionANum());
            }
            if (StringUtils.isNotBlank(filter.getOptionBNum())){
                scoreB += Double.valueOf(filter.getOptionBNum());
            }
            if (StringUtils.isNotBlank(filter.getOptionCNum())){
                scoreC += Double.valueOf(filter.getOptionCNum());
            }
            if (StringUtils.isNotBlank(filter.getOptionDNum())){
                scoreD += Double.valueOf(filter.getOptionDNum());
            }
            if (StringUtils.isNotBlank(filter.getOptionENum())){
                scoreE += Double.valueOf(filter.getOptionENum());
            }
            if (StringUtils.isNotBlank(filter.getOptionFNum())){
                scoreF += Double.valueOf(filter.getOptionFNum());
            }
        }
        scoreA = scoreA * measurementInformationEntity.getScoreA();
        scoreB = scoreB * measurementInformationEntity.getScoreB();
        scoreC = scoreC * measurementInformationEntity.getScoreC();
        scoreD = scoreD * measurementInformationEntity.getScoreD();
        scoreE = scoreE * measurementInformationEntity.getScoreE();
        scoreF = scoreF * measurementInformationEntity.getScoreF();
        Double finalScore = scoreA + scoreB + scoreC + scoreD + scoreE + scoreF;
        measurementInformationEntity.setFinalScore(finalScore);
        return measurementInformationEntity;
    }

    /**
     * 查询测评答案统计
     * @param measurementInformationFilter
     * @return
     */
    @Override
    public List<MeasurementInformationFilter> queryForAnswer(MeasurementInformationFilter measurementInformationFilter) {
        List<MeasurementInformationFilter> list = measurementInformationEntityMapper.queryForAnswer(measurementInformationFilter);
        return list;
    }

    /**
     * 首页图表
     * @return
     */
    @Override
    public List<MeasurementInformationFilter> indexMeasurement() {
        List<MeasurementInformationFilter> list = measurementInformationEntityMapper.indexMeasurement();
        Collections.sort(list, new Comparator<MeasurementInformationFilter>() {
            @Override
            public int compare(MeasurementInformationFilter o1, MeasurementInformationFilter o2) {
                if (o1.getFinalScore()<o2.getFinalScore()){
                    return 1;
                }else {
                    return -1;
                }
            }
        });

        return list;
    }

    /**
     * 首页顶部测评总分
     * @param userEntity
     * @return
     */
    @Override
    public MeasurementInformationFilter indexSumScore(UserEntity userEntity) {
        MeasurementInformationFilter measurementInformationFilter = new MeasurementInformationFilter();
        MeasurementInformationFilter filter ;
        String dateTime = DateUtils.getYear();
        measurementInformationFilter.setEndTime(dateTime);
        if ("admin".equals(userEntity.getUserPermissions())){
            measurementInformationFilter.setEvalutedObj("永泰县");
            filter =  measurementInformationEntityMapper.indexSumScore(measurementInformationFilter);
            return filter;
        }else {
            measurementInformationFilter.setEvalutedObj(userEntity.getUserDepartment());
            filter = measurementInformationEntityMapper.indexSumScore(measurementInformationFilter);
            return filter;
        }
    }

    /**
     * 定时器
     */
    @Override
    @Scheduled(cron = "0 0 0 * * ?")//每天早上0点执行
    public void start() {
        System.out.println("============4============测评开始状态任务star==========================");
        String today = DateUtils.getDate();
        List<MeasurementInformationFilter> list = measurementInformationEntityMapper.query(new MeasurementInformationFilter("0"));
        MeasurementInformationEntity entity = new MeasurementInformationEntity();
        entity.setStatus("1");
        for (MeasurementInformationFilter filter:list) {
            int i = DateUtils.compareDate(today,filter.getStartTime());
            if (i == 1 || i == 0) {
                if (StringUtils.isNotBlank(filter.getTestObj())) {
                    String[] testObj = filter.getTestObj().split("、");
                    int totalPeople = 0;
                    for (String str : testObj) {
                        EvaluateUserFilter evaluateUserFilter = new EvaluateUserFilter();
                        evaluateUserFilter.setDepartment(str);
                        List<EvaluateUserFilter> userList = evaluateUserEntityMapper.query(evaluateUserFilter);
                        totalPeople += userList.size();
//                    for (EvaluateUserFilter userFilter:userList) {
//                        //发短信
//                        com.yunpian.sdk.model.Result<SmsSingleSend> rs = yunpianService.sendSmS(userFilter);
//                        if (rs.getCode() != 0) {
//                            String msg = String.format("验证码发送失败,code=%d", rs.getCode());
//                            throw new ServiceException(msg);
//                        }
//                    }
                    }
                    entity.setTotalPeople(totalPeople + "");
                    entity.setId(filter.getId());
                    int a = measurementInformationEntityMapper.updateByPrimaryKeySelective(entity);
                    if (a == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        System.out.println("更新状态失败");
                    }
                }else {
                    entity.setId(filter.getId());
                    int a = measurementInformationEntityMapper.updateByPrimaryKeySelective(entity);
                    if (a == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        System.out.println("更新状态失败");
                    }
                }
            }
        }
        System.out.println("==========================测评开始状态任务end============================");
    }

    /**
     * 测评状态结束定时器
     */
    @Override
    @Scheduled(cron = "0 0 0 * * ?")
    public void end() {
        System.out.println("======================测评结束状态star====================");
        String today = DateUtils.getDate();
        List<MeasurementInformationFilter> list = measurementInformationEntityMapper.query(new MeasurementInformationFilter("1"));
        MeasurementInformationEntity entity = new MeasurementInformationEntity();
        AnswerFilter answerFilter = new AnswerFilter();
        entity.setStatus("2");
        for (MeasurementInformationFilter filter:list) {
            int i = DateUtils.compareDate(today, filter.getEndTime());
            if (i == 1 || i == 0) {
                answerFilter.setMeasurementId(filter.getId());
                List<AnswerFilter> answerList = answerEntityMapper.queryByRespondents(answerFilter);
                entity.setAnswerPeople(answerList.size()+"");
                entity.setId(filter.getId());
                entity.setScoreA(filter.getScoreA());
                entity.setScoreB(filter.getScoreB());
                entity.setScoreC(filter.getScoreC());
                entity.setScoreD(filter.getScoreD());
                entity.setScoreE(filter.getScoreE());
                entity.setScoreF(filter.getScoreF());
                entity = this.setFinalPoint(entity);
                int a = measurementInformationEntityMapper.updateByPrimaryKeySelective(entity);
                if (a == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    System.out.println("更新状态失败");
                }
            }
        }
        System.out.println("======================测评结束状态end====================");
    }

}
